<!--
 * @Description:It is troublesome to implement radio button group in the form. So it is extracted independently as a separate component
-->
<template>
  <RadioGroup v-bind="attrs" v-model:value="state" button-style="solid" @change="handleChange">
    <template v-for="item in getOptions" :key="`${item.value}`">
      <RadioButton v-if="isBtn" :value="item.value" :disabled="item.disabled">
        {{ item.label }}
      </RadioButton>
      <Radio v-else :value="item.value" :disabled="item.disabled">
        {{ item.label }}
      </Radio>
    </template>
  </RadioGroup>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watchEffect, computed, unref, watch } from 'vue';
import { Radio } from 'ant-design-vue';
import { isFunction, get, omit } from '@pkg/utils';
import { useRuleFormItem } from '@/hooks/component/use-form-item';
import { useAttrs } from '@pkg/use';
import { useI18n } from '@pkg/locale';
import { useUserStore } from '@/store/user';
type OptionsItem = {
  label: string;
  value: string | number | boolean;
  disabled?: boolean;
};

export default defineComponent({
  name: 'ApiRadioGroup',
  components: {
    RadioGroup: Radio.Group,
    RadioButton: Radio.Button,
    Radio,
  },
  props: {
    //接口地址
    api: {
      type: Function as PropType<(arg?: Recordable | string) => Promise<OptionsItem[]>>,
      default: null,
    },
    // 字典code(和api二选一,优先使用)
    dictCode: {
      type: [String] as PropType<string>,
      default: '',
    },
    // 接口参数
    params: {
      type: [Object, String] as PropType<Recordable | string>,
      default: () => ({}),
    },
    value: {
      type: [String, Number, Boolean] as PropType<string | number | boolean>,
    },
    //是否按钮
    isBtn: {
      type: [Boolean] as PropType<boolean>,
      default: false,
    },
    //选项值数字转字符串
    numberToString: { type: Boolean },
    //选项值字符转数字
    stringToNumber: { type: Boolean },
    resultField: { type: String, default: '' },
    labelField: { type: String, default: 'label' },
    valueField: { type: String, default: 'value' },
    immediate: { type: Boolean, default: true },
  },
  emits: ['options-change', 'change'],
  setup(props, { emit }) {
    const options = ref<OptionsItem[]>([]);
    const loading = ref(false);
    const isFirstLoad = ref(true);
    const emitData = ref<any[]>([]);
    const attrs = useAttrs();
    const { t } = useI18n();
    //嵌入到表单中，只需使用挂钩绑定来执行表单验证
    const [state] = useRuleFormItem(props);

    // 处理选项值
    const getOptions = computed(() => {
      const { labelField, valueField, numberToString, stringToNumber } = props;
      return unref(options).reduce((prev, next: Recordable) => {
        if (next) {
          let value = next[valueField];
          if (stringToNumber) {
            value = Number(value);
          }
          prev.push({
            label: next[labelField],
            value: numberToString ? `${value}` : value,
            ...omit(next, [labelField, valueField]),
          });
        }
        return prev;
      }, [] as OptionsItem[]);
    });

    watchEffect(() => {
      props.immediate && fetch();
    });

    watch(
      () => props.params,
      () => {
        !unref(isFirstLoad) && fetch();
      },
      { deep: true },
    );

    async function fetch() {
      const dictCode = props.dictCode;
      if (dictCode) {
        //使用字典作为选项值
        options.value = useUserStore().getDictData[dictCode];
        return;
      }
      const api = props.api;
      if (!api || !isFunction(api)) return;
      options.value = [];
      try {
        loading.value = true;
        const res = await api(props.params);
        if (Array.isArray(res)) {
          options.value = res;
          emitChange();
          return;
        }
        if (props.resultField) {
          options.value = get(res, props.resultField) || [];
        }
        emitChange();
      } catch (error) {
        console.warn(error);
      } finally {
        loading.value = false;
      }
    }

    function emitChange() {
      emit('options-change', unref(getOptions));
    }

    function handleChange(_, ...args) {
      emitData.value = args;
    }

    return { state, getOptions, attrs, loading, t, handleChange };
  },
});
</script>
